package com.zhitian.data;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.csvreader.CsvWriter;

public class RH6900 {
	
	/**获取html文件
	 * @param path   Report文件夹路径
	 * @return
	 */
	public static List<String> getHtml(String path) {
		List<String> list = new ArrayList<>();
		boolean isMatch;
		String regex = "Main.*.html";
		File input = new File(path);
		for(String string : input.list()) {
			isMatch = Pattern.matches(regex, string);
			if(isMatch) {
				list.add(string);
			}
		}
		
		return list;
	}
	
	/**
	 * 创建CsvWriter
	 * @param path  csv文件输出路径
	 * @param header  csv文件的header
	 * @return CsvWriter实例
	 * @throws IOException
	 */
	public static CsvWriter createCsvWriter(String path,String[] header) throws IOException {
		
		FileOutputStream fos = new FileOutputStream(path);
		//在文件中增加BOM，该处的byte[] 可以针对不同编码进行修改
		fos.write(new byte[]{(byte)0xEF, (byte)0xBB, (byte)0xBF});
		CsvWriter writer = new CsvWriter(fos,',',Charset.forName("UTF-8"));
		//String[] header = {"序号","时间","动作","对方","内容"};
		writer.writeRecord(header);
		
		return writer;
	}
	
	/**
	 * 关闭CsvWriter
	 * @param list  CsvWriter对象列表
	 */
	public static void  closeCsvWriter(List<CsvWriter> list) {
		for(CsvWriter csvWriter : list) {
			csvWriter.flush();
			csvWriter.close();
		}
		
	}
	/**
	 * 判断字符串是否全为数字
	 * @param str
	 * @return
	 */
	public static boolean isInteger(String str) {  
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
        return pattern.matcher(str).matches();  
    }
	//删除文件
	public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
	
	/**
	 * 爬取数据并导出csv
	 * @param path  处理的文件夹路径
	 * @param csvOutPath  csv导出目录
	 * @throws IOException 
	 */
	public static void outCsv(String path, String csvOutPath,boolean get_applist,boolean get_contacts,
			boolean get_callsRecord,boolean get_message,boolean get_wechat,boolean get_QQ,
			boolean get_alipay,boolean get_systemInfo) throws IOException {
		List<String> htmls = getHtml(path);
		//准备存储应用列表的csv
		String applist = csvOutPath+"应用列表.csv";
		CsvWriter applist_writer = createCsvWriter(applist, 
				new String[] {"序号","应用"});
		
		//通讯录csv
		String contacts = csvOutPath+"通讯录.csv";
		CsvWriter contacts_writer = createCsvWriter(contacts,
				new String[] {"通讯录类型","序号","姓名","对方号码","数据来源","删除","归属地","卡的类型"});
		
		//通话记录
		String calls = csvOutPath+"通话记录.csv";
		CsvWriter calls_writer = createCsvWriter(calls, 
				new String[] {"通话记录类型","序号","姓名","对方号码","归属地","卡的类型","通话时间","通话时长","数据来源","通话类型","SIM卡","删除"});
		
		//短信
		String message = csvOutPath+"短信.csv";
		CsvWriter message_writer = createCsvWriter(message, 	
				new String[] {"序号","姓名","对方号码","归属地","卡的类型","发送时间","内容","是否已读","服务中心号码","数据来源","短信类型","SIM卡","删除",});
		
		//无线连接账号信息
		String wifi_account_info = csvOutPath+"无限连接账号信息.csv";
		CsvWriter wifi_account_info_writer = createCsvWriter(wifi_account_info, 
				new String[] {"序号","名称","MAC","删除"});
		
		for(String html : htmls) {
			File input = new File(path+html);
			

			
			Document document = Jsoup.parse(input,"UTF-8");
			//获取table标签
			Elements table = document.getElementsByTag("table");
			
			for(Element e : table) {
				if(e.attr("border").equals("1")) {//表内容都在含有border=1属性的table中
					
					Elements captions = e.getElementsByTag("caption");//存放表名的标签
					
					for(Element caption : captions) {
						
						//name是表名，用于对表进行判断
						String form_name = caption.getElementsByTag("a").get(0).ownText();
						String name = form_name.split("\\(")[0];//很奇怪，split 左括号竟然要需要转义
						
						if(name.equals("应用程序列表")) {
							
							for(int i = 0;i<e.getElementsByAttribute("rowspan").size();i+=2) {
								String sequence_num = e.getElementsByAttribute("rowspan").get(i).ownText();
								String app = e.getElementsByAttribute("rowspan").get(i+1).ownText();
								//System.out.println(sequence_num+" : "+app);
								String[] content = {sequence_num,app};
								applist_writer.writeRecord(content);
							}
						}else if (name.equals("未删除通讯录") || name.equals("已删除通讯录")) {
							
							Elements trs = e.getElementsByTag("tbody").get(0).getElementsByTag("tr");
						
							int info_size = trs.size()/(e.getElementsByAttribute("rowspan").size()/2);//保存表格字段数
							int rowspan = e.getElementsByAttribute("rowspan").size()/2;    //保存一个table中有多少条信息
							for(int i = 0;i<rowspan;i++) {
								Element tr = e.getElementsByAttribute("rowspan").get(i*2).parent();
								List<String> content_list = new ArrayList<>();
								content_list.add(name);
								for(int j = 0;j<info_size;j++) {
									if(j % info_size==0) {
										
										if(tr.getElementsByTag("td").size()>2) {
											content_list.add(tr.getElementsByTag("td").get(0).ownText());
											content_list.add(tr.getElementsByTag("td").get(1).ownText());
											content_list.add(tr.getElementsByTag("td").get(3).ownText());
										}else {
											content_list.add(tr.getElementsByTag("td").get(0).ownText());
											content_list.add(tr.getElementsByTag("td").get(1).ownText());
										}
									}else {
										if(tr.getElementsByTag("td").size()>0) {
											String string = tr.getElementsByTag("td").get(0).ownText()+":"+tr.getElementsByTag("td").get(1).ownText();
											content_list.add(string);
										}
									}
									
									
									tr = tr.nextElementSibling();
									
								}
								String[] content = content_list.toArray(new String[11]);
								contacts_writer.writeRecord(content);
							}
						}else if (isInteger(name.split("_")[0])) {//短信和通话记录的表
							Elements trs = e.getElementsByTag("tbody").get(0).getElementsByTag("tr");
							
							
							int info_size = trs.size()/(e.getElementsByAttribute("rowspan").size()/2);//保存表格字段数
							int rowspan = e.getElementsByAttribute("rowspan").size()/2;    //保存一个table中有多少条信息
							
							for(int i = 0;i<rowspan;i++) {
								boolean is_message = false;
								Element tr = e.getElementsByAttribute("rowspan").get(i*2).parent();//这里i一定要X2因为每个rt的rowspan有两个
								List<String> content_list = new ArrayList<>();
								content_list.add(name);
								for(int j = 0;j<info_size;j++) {
									if(j % info_size==0) {
										content_list.add(tr.getElementsByTag("td").get(0).ownText());
										content_list.add(tr.getElementsByTag("td").get(1).ownText());
										content_list.add(tr.getElementsByTag("td").get(3).ownText());
									}else {
										if(tr.getElementsByTag("td").size()>0) {
											
											if(tr.getElementsByTag("td").get(0).ownText().equals("短信类型")) {
												is_message = true;
											}
											content_list.add(tr.getElementsByTag("td").get(1).ownText());
										}else {
											content_list.add("");
										}
									}

									tr = tr.nextElementSibling();
								}
								String[] content = content_list.toArray(new String[15]);
								if(is_message)
								    message_writer.writeRecord(content);
								else
									calls_writer.writeRecord(content);
							}
						}else if (name.equals("WIFI信息") || name.equals("WIFI热点痕迹")) {
							Elements trs = e.getElementsByTag("tbody").get(0).getElementsByTag("tr");
							
							int info_size = trs.size()/(e.getElementsByAttribute("rowspan").size()/2);//保存表格字段数
							int rowspan = e.getElementsByAttribute("rowspan").size()/2;    //保存一个table中有多少条信息
							
							for(int i=0;i<rowspan;i++) {
								Element tr = e.getElementsByAttribute("rowspan").get(i*2).parent();//找到rowspan定位tr
								List<String> content_list = new ArrayList<>();
								content_list.add(name);
								for(int j=0;j<info_size;j++) {
									if(j%info_size==0) {
										if(tr.getElementsByTag("td").size()>2) {
											content_list.add(tr.getElementsByTag("td").get(0).ownText());
											content_list.add(tr.getElementsByTag("td").get(1).ownText());
											content_list.add(tr.getElementsByTag("td").get(3).ownText());
										}else {
											content_list.add(tr.getElementsByTag("td").get(0).ownText());
											content_list.add(tr.getElementsByTag("td").get(1).ownText());
										}
									}else {
										if(tr.getElementsByTag("td").size()>0) {
											String string = tr.getElementsByTag("td").get(0).ownText()+":"+tr.getElementsByTag("td").get(1).ownText();
											content_list.add(string);
										}
									}
									
									tr = tr.nextElementSibling();
								}
								String[] content = content_list.toArray(new String[11]);
								wifi_account_info_writer.writeRecord(content);
							}
							
							
						}

					}
					
				}
				
			}
			
			Elements ps = document.getElementsByTag("p");
			if(ps.size()>0) {
				//System.out.println(ps);
			}
			
			
		}
		List<CsvWriter> list = new ArrayList<>();
		list.add(applist_writer);
		list.add(contacts_writer);
		list.add(calls_writer);
		list.add(message_writer);
		list.add(wifi_account_info_writer);
		closeCsvWriter(list);
		
		//删除不需要的文件
		if(!get_applist) {
			deleteFile(applist);
		}
		if(!get_contacts) {
			deleteFile(contacts);
		}
		if(!get_callsRecord) {
			deleteFile(calls);
		}
		if(!get_systemInfo) {
			deleteFile(wifi_account_info);
		}
		
	}
	

	
	public static void main(String[] args) {
		String path = "D:\\AHTMLDATA\\111\\oppo\\oppo_Report\\";
		String csvOutPath = "D:/csvPath3/";
		
		String x = "证据信息";
		x.split("\\(");
		try {
			//outCsv(path, csvOutPath);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
